﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WS1.Filets;
using WS1.Models;
using WS1.Services;

namespace WS1.Controllers
{
    [BasicAuthentication("staff","BCLyon2024")]
    public class ProductsController : ApiController
    {
        // GET: api/Products
        public AppResult<IEnumerable<Products>> Get()
         {
            var result = new AppResult<IEnumerable<Products>>();
            using (var service = new ProductsServices())
            {
                var products = service.GetAll();
                result.Data = products;
            }
            return result;
        }

        // GET: api/Products/5
        public AppResult<Products> Get(int id)
        {
            var result = new AppResult<Products>();

            using (var service = new ProductsServices())
            {
                var product = service.Get(id);
                result.Data = product;
            }
            return result;
        }

        public AppResult Post([FromBody] Products product)
        {

            var result = new AppResult();
            if (ModelState.IsValid)
            {


                try
                {
                    using (var service = new ProductsServices())
                    {
                        service.Add(product);
                    }
                }
                catch (System.Exception ex)
                {
                    result.IsSuccess = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.ModelError(ModelState);
            }
            return result;
        }

        public AppResult Put(int id, [FromBody] Products product)
        {
            var result = new AppResult();
            try
            {
                using (var service = new ProductsServices())
                {
                    service.Update(id, product);
                }
            }
            catch (System.Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
            }
            return result;

        }

        public AppResult Delete(int id)
        {
            var result = new AppResult();
            try
            {
                using (var service = new ProductsServices())
                {
                    service.Remove(id);
                }
            }
            catch (System.Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
            }
            return result;
        }
       
       
    }
}
